package com.itheima.controller.v1;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.controller.v1.api.UserControllerApi;
import com.itheima.pojo.SysUser;
import com.itheima.service.SysUserService;
import com.itheima.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController implements UserControllerApi {

    @Autowired
    private SysUserService sysUserService;


    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    @PostMapping("/in")
    public R login(@RequestBody SysUser sysUser) {

        //0.从seesion中获取验证码  匹配前端发来的验证码
//        HttpSession session = request.getSession();
//        String code = (String) session.getAttribute("code");
        String code = (String) redisTemplate.opsForValue().get(sysUser.getUuid());
        if(!sysUser.getCode().equals(code)){
            return R.error("验证码错误");

        }        //1.判断下参数是否合法
        if (sysUser == null){
            return R.error("参数不合法");
        }
        //2.根据用户名查询用户对象
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName,sysUser.getUserName());
        SysUser user = sysUserService.getOne(wrapper);
        //3.加密密码
        String password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        //4.使用加密后的密码和数据库的密码进行匹配校验
        if(!password.equals(user.getPassword())){
            return R.error("密码错误");
        }
        //5.存储到session中
        //6.返回用户信息即可
        String jwt = JwtUtil.createJWT(user.getUserId().toString(), user.getUserName(), 1000 * 60 * 24 * 5l);

        return new R(1,"登录成功",jwt);
    }
}
